package com.tapstitch.scm.pms.web.facade;

import com.bluebuck.quickboot.alert.AlertMsgConfig;
import com.bluebuck.quickboot.alert.AlertMsgManager;
import com.bluebuck.quickboot.core.JsonUtil;
import com.bluebuck.quickboot.core.ServletUtils;
import com.bluebuck.quickboot.core.SpringUtils;
import com.bluebuck.quickboot.core.TraceUtil;
import com.bluebuck.sso.client.admin.auth.model.LoginUser;
import com.bluebuck.sso.client.admin.auth.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
public class AlertFacade {

    @Value("${feishu.alert-id}")
    private String alertAppId;

    @Value("${feishu.alert-secret}")
    private String alertSecret;

    @Value("${feishu.sys-error-chat-id}")
    private String sysErrorChatId;

    @Autowired
    private LoginService loginService;

    /**
     * 线程池发送消息 异步处理   线程池满时丢弃
     */
    private final ThreadPoolExecutor executors = new ThreadPoolExecutor(5, 5, 5, TimeUnit.MINUTES,
            new LinkedBlockingDeque<>(50), Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardPolicy());

    @PostConstruct
    public void init() {
        AlertMsgManager.init(new AlertMsgConfig(alertAppId, alertSecret, !SpringUtils.isProdEnv()));
    }

    public void sendMsg(Exception e) {
        StringBuilder msg = new StringBuilder();
        msg.append("系统出现异常\r\n");
        if (ServletUtils.getRequestAttributes() != null) {
            HttpServletRequest request = ServletUtils.getRequest();
            LoginUser user = loginService.getLoginUser();
            if (user != null) {
                msg.append("访问用户:" + user.getRealName() + "\r\n");
            }
            msg.append("访问地址:" + request.getRequestURI() + "\r\n");
            msg.append("参数:" + JsonUtil.toJSONString(request.getParameterMap()) + "\r\n");
        }
        msg.append("TraceId:" + TraceUtil.getTraceId() + "\r\n");
        msg.append("异常信息:" + e.getMessage() + "\r\n");
        msg.append(convertExceptionToContent(e));
        executors.submit(() -> {
            AlertMsgManager.getSender(alertAppId).sendCardMsg(sysErrorChatId, "系统出现异常", e.getMessage(), msg.toString());
        });
    }

    private String convertExceptionToContent(Exception exception) {
        if (exception == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        sb.append("<br>异常：" + exception.getClass().getName() + " " + exception.getMessage()).append("<br>堆栈：<br>");
        StringWriter sw = new StringWriter(500);
        exception.printStackTrace(new PrintWriter(sw));
        String stackTrace = sw.toString();
        sb.append(stackTrace);
        return sb.append(exception.getMessage()).toString();
    }
}
